package demo2;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张宇田
 * Date: 2025-08-16
 * Time: 23:24
 */
public class MyArrayList implements IList{
    public int [] arr ;
    public int usesized = 0;

    public MyArrayList(){
        arr = new int[10];
    }

    @Override
    public void add(int data) {
        if(isFull()){
            grow();
        }
        arr[usesized] = data; //  1 2 3 4
        usesized ++;
    }
    private void grow(){
        arr = Arrays.copyOf(arr,arr.length*2);
    }
    @Override
    public void add(int pos, int data) {
        // 这里等于us 相当于add
        if (pos < 0 || pos >usesized){
            return;
        }
        if(isFull()){
            grow();
        }
        //重构往前移动
        for (int i = usesized - 1;i >= pos ; i--){
            arr[i+1] = arr[i];
        }
        arr[pos] = data;
        usesized++;
    }

    @Override
    //找到tofind 返回true
    public boolean contains(int toFind) {
        //注意遍历数组要用us
        for (int i = 0 ; i<usesized ; i++){
            if(arr[i] == toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    //找到数据toFind 返回下标
    public int indexOf(int toFind) {

        if(isEmpty()){
            return -1;
        }
        for (int i = 0 ; i<usesized ; i++){
            if(arr[i] == toFind){
                return i;
            }
        }

        return -1;
    }

    @Override
    public int get(int pos) {
        if (pos < 0 || pos >usesized -1){
            return -1;
        }
        if(isEmpty()){
            return -1;
        }
        return arr[pos];
    }

    @Override
    public void set(int pos, int value) {
        if (pos < 0 || pos >usesized -1){
            return ;
        }

        arr[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
        for (int i = 0 ; i<usesized ; i++){
            if(arr[i] == toRemove){
                //不用走到最后一位 前一位就行 不然超了最后一位
                for (int j = i ; j < usesized - 1 ; j++){
                    arr[j] = arr[j+1];
                }
                usesized--;
                return;
            }
        }

    }

    @Override
    public int size() {
        return usesized;
    }

    @Override
    public void clear() {
        usesized = 0;
    }

    @Override
    public void display() {
        for(int i = 0 ; i< usesized ; i++){
            System.out.print(arr[i] + " ");
        }
    }

    @Override
    public boolean isFull() {
        return usesized == arr.length ;
    }

    @Override
    public boolean isEmpty() {
        return usesized == 0;
    }
}
